<template>
  <el-select-v2
    v-model="value"
    :multiple="props.multiple"
    :options="options"
    filterable
    remote
    clearable
    :remote-method="remoteMethod"
    :style="props.style"
    :loading="loading"
    :value-key="props.value"
  />
</template>

<script setup lang="ts" name="selectV3">
import { ref, watch, onBeforeMount } from "vue";

const props = defineProps({
  modelValue: {
    type: [String, Number]
  },
  exclude_id: {
    type: [String, Number, Object]
  },
  url: {
    type: [Function],
    required: true
  },
  props: {
    type: [Object],
    default: () => {
      return {
        label: "name",
        value: "id"
      };
    }
  },
  multiple: {
    type: Boolean,
    default: false
  },
  data: {
    type: [Object],
    default: () => {
      return {
        label: "无",
        value: 0
      };
    }
  },
  style: {
    type: [String],
    default: "min-width:211px;"
  }
});

const data = [];
data.push(props.data);
const value = ref("");
const options = ref(data);
const loading = ref(false);

let timeoutId = null;
const remoteMethod = (name?: string, id) => {
  if (timeoutId) {
    clearTimeout(timeoutId);
  }

  const label = props.props.label;
  const val = props.props.value;
  const params = {};
  params[label] = name;
  params[val] = id;
  params.exclude_id = props.exclude_id;
  timeoutId = setTimeout(
    () => {
      loading.value = true;
      props.url(params).then(response => {
        options.value = [];
        const items = [];
        if (!name) {
          items.push(props.data);
        }

        response.data.list.forEach(item => {
          items.push({
            label: item[label],
            value: item[val]
          });
        });

        options.value = items;
        items.find(item => {
          if (item.value == id) {
            value.value = item.value;
          }
        });

        loading.value = false;
      });
    },
    id ? 100 : 300
  );
};

watch(
  () => props.modelValue,
  newValue => {
    if (value.value == newValue) return;
    value.value = newValue.toString();
    remoteMethod("", newValue);
  }
);

const emits = defineEmits(["update:modelValue"]);
watch(value, newValue => {
  emits("update:modelValue", newValue);
});

onBeforeMount(() => {
  remoteMethod("", props.modelValue > 0 ? props.modelValue : "");
});
</script>
0
